package com.dmooo.yxmmerchant.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import com.common.mvpbase.BasePresenter;
import com.common.mvpbase.BaseView;
import com.common.util.BaseActivityManager;
import com.common.util.SPUtils;
import com.common.util.StartActivityUtil;
import com.common.util.ToastUtil;
import com.dmooo.yxmmerchant.MainActivity;
import com.dmooo.yxmmerchant.R;
import com.dmooo.yxmmerchant.common.Config;
import com.dmooo.yxmmerchant.util.CommonUtils;
import com.dmooo.yxmmerchant.view.ui.ChatActivity;
import com.dmooo.yxmmerchant.view.ui.LoginActivity;
import com.github.anzewei.parallaxbacklayout.ParallaxBack;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.hyphenate.chat.EMClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Properties;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 基类Activity的封装
 * 一般使用mvp模式的话会在BaseActivity中进行P和V的初始化绑定
 */
@ParallaxBack
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView {
    protected T mPresenter;
    protected Activity mContext;
    Unbinder unbind;
    protected String token = "",merchant_id="";
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.slide_in_right, R.anim.no_slide);
        setContentView(getLayout());
        unbind = ButterKnife.bind(this);
        token = SPUtils.get(this, Config.TOKEN, "").toString();
        merchant_id=SPUtils.get(this,Config.UID,"").toString();
        mContext = this;
        createPresenter();
        BaseActivityManager.getInstance().addActivity(this);
        initEventAndData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if("1".equals(SPUtils.get(this,"new_mes","0").toString())){
            if(BaseActivityManager.getInstance().currentActivity() instanceof ChatActivity){
                BaseActivityManager.getInstance().currentActivity().finish();
            }
            SPUtils.put(this,"new_mes","0");
            Bundle bundle=new Bundle();
            bundle.putString("name", SPUtils.get(this,"name","").toString());
            bundle.putString("uuid", SPUtils.get(this,"uuid","").toString());
            StartActivityUtil.startActivity(this,ChatActivity.class,bundle);
        }
    }
    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.no_slide, R.anim.slide_out_right);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        unbind.unbind();
        BaseActivityManager.getInstance().removeActivity(this);
    }
    public void gotoSet() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

    }
    protected abstract int getLayout();

    protected abstract void initEventAndData();

    protected abstract void createPresenter();
    protected boolean checkPermission(String permission) {
        if (XXPermissions.isHasPermission(this, permission)) {
            return true;
        }
        return false;
    }
    public static boolean isPermissionOpen(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return NotificationManagerCompat.from(context).getImportance() != NotificationManager.IMPORTANCE_NONE;
        }
        return NotificationManagerCompat.from(context).areNotificationsEnabled();
    }
    protected void requestPermission(String permission,final String name) {
        XXPermissions.with(this)
                .permission(permission)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
//                        dialog.show();

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if(quick){
                            final AlertDialog.Builder normalDialog =new AlertDialog.Builder(BaseActivityManager.getInstance().currentActivity());
                            normalDialog.setTitle("开启权限引导");
                            normalDialog.setMessage(name+"为应用必要权限，您之前已永久拒绝，是否需要引导您去手动开启权限");
                            normalDialog.setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0, int arg1) {
                                    XXPermissions.gotoPermissionSettings(BaseActivityManager.getInstance().currentActivity());
                                }									});
                            normalDialog.setNegativeButton("下一次", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0, int arg1) {
                                }
                            });
                            normalDialog.show();
                        }else{
                            ToastUtil.getInstance().showErrorMsg("应用未获得该权限,将影响部分功能使用");
                        }
                    }
                });
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }
    @Override
    public void errorMsg(String msg) {
        if (msg.contains("商户不存在(504)")) {
            if ("".equals(SPUtils.get(this, Config.TOKEN, "").toString())) {
                ToastUtil.getInstance().showErrorMsg("请先登录");
            } else {
                ToastUtil.getInstance().showErrorMsg("您的账号在其他设备登录，请重新登录");
            }
            EMClient.getInstance().logout(true);
            BaseActivityManager.getInstance().finishAllActivity();
            StartActivityUtil.startActivity(this, LoginActivity.class);
        } else {
            ToastUtil.getInstance().showErrorMsg(msg);
        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_HOME){
            Intent intent = new Intent();
            intent.setAction("android.intent.action.MAIN");
            intent.addCategory("android.intent.category.HOME");
            startActivity(intent);
            return true;
        }
        if(keyCode==KeyEvent.KEYCODE_BACK&& BaseActivityManager.getInstance().currentActivity() instanceof MainActivity){
            Intent intent = new Intent();
            intent.setAction("android.intent.action.MAIN");
            intent.addCategory("android.intent.category.HOME");
            startActivity(intent);
            return true;
        }else{
            if(keyCode==KeyEvent.KEYCODE_DEL){
                return true;
            }
            if(!isSoftShowing()) {
                Handler mHandler = new Handler();
                Runnable r1 = new Runnable() {
                    @Override
                    public void run() {
                        BaseActivityManager.getInstance().currentActivity().finish();
                    }
                };
                mHandler.postDelayed(r1, 100);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    private boolean isSoftShowing() {
        int screenHeight = getWindow().getDecorView().getHeight();
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return screenHeight * 2 / 3 > rect.bottom;
    }
    protected void setStatusBar(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(color);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (color == Color.WHITE) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            if (isFlyme()) {
                CommonUtils.setMeizuStatusBarDarkIcon(this, true);
            } else if (isMIUI()) {
                CommonUtils.setMiuiStatusBarDarkMode(this, true);
            } else if (Build.MANUFACTURER.equalsIgnoreCase("OPPO")) {
                CommonUtils.setOPPOStatusTextColor(true, this);
            } else {
            }
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }

    /**
     * 判断手机是否是魅族
     *
     * @return
     */
    private static boolean isFlyme() {
        try {
            final Method method = Build.class.getMethod("hasSmartBar");
            return method != null;
        } catch (final Exception e) {
            return false;
        }
    }

    /**
     * 判断手机是否是小米
     *
     * @return
     */
    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";

    private static boolean isMIUI() {
        Properties prop = new Properties();
        boolean isMIUI;
        try {
            prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        isMIUI = prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
//        SPUtils.getInstance().putCacheData("isMIUI",isMIUI);//保存是否MIUI
        return isMIUI;
    }
    public static String getRealFilePath(final Context context, final Uri uri) {
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
